import os
import sys
import logging
from pathlib import Path


def validate_file(file_path: str) -> bool:
	"""跨平台文件验证（Windows/MacOS/Linux通用）"""
	if not file_path:
		return False
	
	path = Path(file_path)
	
	# 基础校验
	if not (path.exists() and path.is_file()):
		logging.warning(f"文件不存在或不是常规文件: {file_path}")
		return False
	
	# 扩展名校验
	if path.suffix.lower() not in ['.xlsx', '.xls']:
		logging.warning(f"不支持的文件类型: {path.suffix}")
		return False
	
	# 文件大小限制（最大500MB）
	if path.stat().st_size > 500 * 1024 * 1024:
		logging.warning(f"文件超过大小限制: {path.stat().st_size / 1024 / 1024:.2f}MB")
		return False
	
	# 文件占用检测（跨平台方法）
	if is_file_locked(path):
		logging.warning("文件被其他程序占用")
		return False
	
	return True


def is_file_locked(file_path: Path) -> bool:
	"""检测文件是否被占用（通用方法）"""
	try:
		# Windows系统专用检测
		if sys.platform == 'win32':
			return _windows_file_lock_check(file_path)
		
		# Unix-like系统检测
		return _unix_file_lock_check(file_path)
	except Exception as e:
		logging.error(f"文件占用检测失败: {str(e)}")
		return False


def _windows_file_lock_check(file_path: Path) -> bool:
	"""Windows系统专用文件占用检测"""
	try:
		# 尝试以追加模式打开文件
		with open(file_path, 'a') as f:
			pass
		return False
	except PermissionError:
		return True
	except Exception as e:
		logging.warning(f"Windows文件检测异常: {str(e)}")
		return False


def _unix_file_lock_check(file_path: Path) -> bool:
	"""Unix-like系统文件检测"""
	try:
		# 检查文件是否被其他进程打开
		if sys.platform == 'darwin':
			# MacOS使用lsof命令
			exit_code = os.system(f"lsof {file_path} > /dev/null")
			return exit_code == 0
		else:
			# Linux使用fuser命令
			exit_code = os.system(f"fuser {file_path} > /dev/null 2>&1")
			return exit_code == 0
	except Exception as e:
		logging.warning(f"Unix文件检测异常: {str(e)}")
		return False


# 保留原文件选择器
def get_excel_file(parent=None):
	from PyQt6.QtWidgets import QFileDialog
	return QFileDialog.getOpenFileName(
		parent,
		"选择Excel文件",
		"",
		"Excel Files (*.xlsx *.xls);;All Files (*)"
	)[0] if validate_file else None
